/**
 * XmlParserUtil.java
 * author: yujiakui
 * 2017年9月1日
 * 上午8:27:40
 */
package com.ctim.service.test.tools;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * @author yujiakui
 *
 *         上午8:27:40
 *
 *         XML解析工具
 */
public class XmlParserUtil {

	/**
	 * 解析xml文件，目前只支持解析2层
	 *
	 * @param fileName
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static List parse(String fileName, List<String> useCaseExecIds) {
		File inputXml = new File(fileName);
		List list = new ArrayList();
		SAXReader saxReader = new SAXReader();
		try {
			Document document = saxReader.read(inputXml);
			Element employees = document.getRootElement();
			for (Iterator i = employees.elementIterator(); i.hasNext();) {
				Element employee = (Element) i.next();
				String id = employee.attribute("id").getValue();
				// 获取对应的属性id
				if (null != useCaseExecIds && useCaseExecIds.size() != 0
						&& !useCaseExecIds.contains(id)) {
					continue;
				}

				Map map = new HashMap();
				Map tempMap = new HashMap();
				for (Iterator j = employee.elementIterator(); j.hasNext();) {
					Element node = (Element) j.next();
					// System.out.println(node.nodeCount());
					if (node.nodeCount() > 1) {
						Map temMap2 = new HashMap<>();
						for (Iterator k = node.elementIterator(); k.hasNext();) {
							Element node2 = (Element) k.next();
							temMap2.put(node2.attribute("key").getValue(), node2.getText());
						}
						tempMap.put(node.getName(), temMap2);
					} else {
						tempMap.put(node.getName(), node.getText());
					}
				}
				map.put(employee.getName(), tempMap);
				list.add(map);
			}
		} catch (DocumentException e) {
			System.out.println(e.getMessage());
		}
		return list;
	}

}
